package com.epidata.exam.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Model;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.inject.Inject;
import javax.inject.Named;

import com.epidata.exam.model.Employee;
import com.epidata.exam.model.ReciboDeSueldo;
import com.epidata.exam.service.EmployeeRegistration;

// The @Model stereotype is a convenience mechanism to make this a request-scoped bean that has an
// EL name
// Read more about the @Model stereotype in this FAQ:
// http://sfwk.org/Documentation/WhatIsThePurposeOfTheModelAnnotation
@Model
public class EmployeeController extends BaseController{

	private static final int CANTIDAD_RECIBOS_DEFAULT = 3;

	@Inject
	private Logger log;

	@Inject
	private EmployeeRegistration employeeRegistration;

	private Employee newEmployee;

	private BigDecimal importe;

	private Date date;

	private List<ReciboDeSueldo> recibos ;



	@Produces
	@Named
	public Employee getNewEmployee() {
		return newEmployee;
	}


	public void register() throws Exception {
		try {
			log.info("Comienzo registro");
			log.info("Recibos agregados " + getRecibos().size());

			addRecibos();

			employeeRegistration.register(newEmployee);

			FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "Registered!", "Registration successful");
			facesContext.addMessage(null, m);
			initNewEmployee();
			initRecibos();
		} catch (Exception e) {
			e.printStackTrace();
			String errorMessage = getRootErrorMessage(e);
			FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Registration unsuccessful");
			facesContext.addMessage(null, m);
		}
	}


	private void addRecibos() {
		for(ReciboDeSueldo recibo : getRecibos()){
			newEmployee.addRecibo(recibo);
		}
	}


	@PostConstruct
	public void initNewEmployee() {
		newEmployee = new Employee();
		initRecibos();
		importe = null;
		date = null;
	}

	private void initRecibos() {
		setRecibos(new ArrayList<ReciboDeSueldo>(CANTIDAD_RECIBOS_DEFAULT));
		for(int i = 0;i < CANTIDAD_RECIBOS_DEFAULT; i++){
			getRecibos().add(new ReciboDeSueldo());
		}
	}


	public BigDecimal getImporte() {
		return importe;
	}

	public void setImporte(BigDecimal importe) {
		this.importe = importe;
	}


	public Date getDate() {
		return date;
	}


	public void setDate(Date date) {
		this.date = date;
	}


	public List<ReciboDeSueldo> getRecibos() {
		return recibos;
	}


	public void setRecibos(List<ReciboDeSueldo> recibos) {
		this.recibos = recibos;
	}


}
